package com.ma.chapter8.jdkpool;

import lombok.extern.slf4j.Slf4j;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.ma.util.Sleeper.sleep;

/**
 * @ClassName TestTimer
 * @Author: mayongqiang
 * @DATE 2022/3/22 20:23
 * @Description: jdk1.3定时器 串行
 */
@Slf4j(topic = "m.TestTimer")
public class TestTimer {
    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        log.debug("start...");
        //pool.scheduleAtFixedRate(() -> {
        //    log.debug("running...");
        //    sleep(2);
        //}, 1,1,TimeUnit.SECONDS);

        pool.scheduleWithFixedDelay(() -> {
            log.debug("running...");
            sleep(2);
        }, 1, 1, TimeUnit.SECONDS);

    }

    private static void method1(ScheduledExecutorService pool) {
        pool.schedule(() -> {
            log.debug("task1");
            int i = 10 / 0;
        }, 1, TimeUnit.SECONDS);
        pool.schedule(() -> log.debug("task2"), 1, TimeUnit.SECONDS);
    }

    private static void method1() {
        Timer timer = new Timer();
        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                log.debug("1");
                sleep(2);
            }
        };
        TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                log.debug("1");

            }
        };

        log.debug("start...");
        timer.schedule(task1, 1000);
        //串行  没有同时执行任务2  而是任务一完成后执行
        timer.schedule(task2, 1000);
    }
}
